package com.pine.common.excel;

import com.pine.common.util.time.TimeUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/**
 * excel服务
 *
 * @author pine manage
 * @since 2024-10-14
 */
public interface ExcelService<Query> {

    /**
     * 响应字符编码
     */
    String RESPONSE_CHARACTER_ENCODING = "utf-8";
    String APPLICATION_OCTET_STREAM_VALUE = "application/octet-stream";

    String RESPONSE_HEADER_CONTENT_DISPOSITION_KEY = "Content-disposition";
    String RESPONSE_HEADER_CONTENT_DISPOSITION_VALUE_PATTERN = "attachment;filename=%s.xlsx";

    /**
     * 最大导出数量
     */
    long MAX_EXPORT_SIZE = 1000_000L;

    /**
     * 导入
     */
    default void importExcel(MultipartFile file) {
        throw new UnsupportedOperationException();
    }

    /**
     * 获取导入模版
     */
    default void importTpl(HttpServletResponse response) {
        throw new UnsupportedOperationException();
    }

    /**
     * 同步导出
     */
    default void syncExport(HttpServletResponse response, Query query) {
        throw new UnsupportedOperationException();
    }

    /**
     * 异步导出
     */
    default void asyncExport(Query query) {
        throw new UnsupportedOperationException();
    }

    /**
     * 生成文件名
     *
     * @param fileNamePrefix 文件名前缀
     * @return 文件名
     */
    default String generateFileName(String fileNamePrefix) {
        String fileName = fileNamePrefix + TimeUtil.parse(LocalDateTime.now());
        // URLEncoder.encode 可以防止中文乱码
        fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        return fileName;
    }

    /**
     * 设置响应头信息
     *
     * @param response       响应
     * @param generateFileName 文件名前缀
     */
    default void setResponseAndHeaderInfo(HttpServletResponse response, String generateFileName) {
        // 设置相应格式
        response.setContentType(APPLICATION_OCTET_STREAM_VALUE);
        // 响应编码
        response.setCharacterEncoding(RESPONSE_CHARACTER_ENCODING);
        response.setHeader(RESPONSE_HEADER_CONTENT_DISPOSITION_KEY, String.format(RESPONSE_HEADER_CONTENT_DISPOSITION_VALUE_PATTERN, generateFileName(generateFileName)));
    }
}
